// 配置路由的地方

// 引入Vue
import Vue from "vue";
// 引入VueRouter
import VueRouter from 'vue-router';
// 使用插件
Vue.use(VueRouter);
// 引入store
import store from '@/store';

// 引入路由组件
import Home from '@/views/Home'
import Login from '@/views/Login'
import Search from '@/views/Search'
import Register from '@/views/Register'
import Detail from '@/views/Detail'
import AddCartSuccess from '@/views/AddCartSuccess'
import ShopCart from '@/views/ShopCart'
import Trade from '@/views/Trade'
import Pay from '@/views/Pay'
import PaySuccess from '@/views/PaySuccess'
import Center from '@/views/Center'

// 引入二级路由组件
import MyOrder from '@/views/Center/myOrder'
import GroupOrder from '@/views/Center/groupOrder'

// 保存一份原方法
let originPush = VueRouter.prototype.push;
let originReplace = VueRouter.prototype.replace;
// 重写push|replace方法
// 第一个参数：告诉原来push，跳转到地址（传递哪些参数）
VueRouter.prototype.push = function (location, resolve, reject) {
    if (resolve && reject) {
        originPush.call(this, location, resolve, reject);
    } else {
        originPush.call(this, location, () => { }, () => { });
    }
}

VueRouter.prototype.replace = function (location, resolve, reject) {
    if (resolve && reject) {
        originReplace.call(this, location, resolve, reject);
    } else {
        originReplace.call(this, location, () => { }, () => { });
    }
}

// 配置路由
let router = new VueRouter({
    routes: [
        {
            path: '/home',
            component: Home,
            meta: { showFooter: true }
        },
        {
            path: '/login',
            component: Login,
            meta: { showFooter: false }
        },
        {
            path: '/search/:keyword?',
            component: Search,
            meta: { showFooter: true },
            name: 'search',
            props: ($route) => {
                return { keyword: $route.params.keyword, k: $route.query.k }
            }
        },
        {
            path: '/register',
            component: Register,
            meta: { showFooter: false }
        },
        {
            path: '/detail/:skuid',
            component: Detail,
            meta: { showFooter: false }
        },
        {
            path: '/addcartsuccess',
            component: AddCartSuccess,
            name: 'addcartsuccess',
            meta: { showFooter: true }
        },
        {
            path: '/shopcart',
            component: ShopCart,
            meta: { showFooter: true }
        },
        {
            path: '/trade',
            component: Trade,
            meta: { showFooter: true },
            // 路由独享守卫
            beforeEnter: (to, from, next) => {
                // 从购物车来放行
                if (from.path == '/shopcart') {
                    next();
                } else {
                    // 从哪来回哪去
                    next(false);
                }
            }
        },
        {
            path: '/pay',
            component: Pay,
            meta: { showFooter: true },
            // 路由独享守卫
            beforeEnter: (to, from, next) => {
                // 从购物车来放行
                if (from.path == '/trade') {
                    next();
                } else {
                    // 从哪来回哪去
                    next(false);
                }
            }
        },
        {
            path: '/paysuccess',
            component: PaySuccess,
            meta: { showFooter: true }
        },
        {
            path: '/center',
            component: Center,
            meta: { showFooter: true },
            redirect: '/center/myorder',
            children: [
                {
                    path: 'myorder',
                    component: MyOrder
                },
                {
                    path: 'grouporder',
                    component: GroupOrder
                },
            ]
        },
        // 重定向
        {
            path: '/',
            redirect: '/home'
        }
    ],
    // 滚动行为
    scrollBehavior(to, from, savePosition) {
        // 代表竖向滚动条在最上面
        return { y: 0 }
    }
});

// 全局守卫（的前置守卫：在路由跳转之前进行判断）
// to:跳转到哪个路由信息
// from:从哪个路由来的
// next:放行函数 next()全部放行 next('/login')放行到指定的路由中
router.beforeEach(async (to, from, next) => {
    // 如果有token，则用户登录过了
    let token = store.state.user.token;
    let name = store.state.user.userInfo.name;
    if (token) {
        // 登录过了还想去login，不行，导航到home
        if (to.path == '/login') {
            next('/home');
        } else {
            // 登录了，但去的不是login
            if (name) {
                next();
            } else {
                try {
                    await store.dispatch('getUserInfo');
                    next();
                } catch (error) {
                    // token失效，但token仍然存在，因此要清除
                    await store.dispatch('userLogout');
                    next('/login');
                }
            }
        }
    } else {
        // 未登录：不能去交易、支付相关、个人中心，如果去这些那就去登录页
        let toPath = to.path;
        if (toPath == '/trade' || toPath.indexOf('/pay') != -1 || toPath.indexOf('/center') != -1) {
            next('/login');
        } else {
            next();
        }
    }
});

export default router;